package com.small.common.config.admin.impl;

import com.small.common.base.BaseConstants;
import com.small.common.config.admin.IAdminInfo;
import com.small.common.util.Encoding;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * 作者: fenny
 * 邮箱: 893146555@qq.com
 * 时间: 2017/10/17 17:04
 * 描述: 从jwt中获取管理员用户信息
 */
@Component
public class AdminJwtInfoImpl implements IAdminInfo {

    @Override
    public long getId(HttpServletRequest request) {
        String value = request.getHeader(BaseConstants.KEY_ID);
        return StringUtils.isEmpty(value) ? 0 : Long.parseLong(value);
    }

    @Override
    public String getAccount(HttpServletRequest request) {
        String value = request.getHeader(BaseConstants.KEY_ACCOUNT);
        return StringUtils.isEmpty(value) ? "" : value;
    }

    @Override
    public String getName(HttpServletRequest request) {
        return decode(request.getHeader(BaseConstants.KEY_NAME));
    }

    @Override
    public String getToken(HttpServletRequest request) {
        String value = request.getHeader(BaseConstants.KEY_TOKEN);
        return StringUtils.isEmpty(value) ? "" : value;
    }

    @Override
    public int getIsSystem(HttpServletRequest request) {
        String value = request.getHeader(BaseConstants.KEY_IS_SYSTEM);
        return StringUtils.isEmpty(value) ? 0 : Integer.parseInt(value);
    }

    @Override
    public String getRoles(HttpServletRequest request) {
        String value = request.getHeader(BaseConstants.KEY_ROLES);
        return StringUtils.isEmpty(value) ? "" : value;
    }

    @Override
    public String getData(HttpServletRequest request) {
        return decode(request.getHeader(BaseConstants.KEY_DATA));
    }

    private String decode(String value) {
        try {
            value = StringUtils.isEmpty(value) ? "" : URLDecoder.decode(value, Encoding.UTF8);
        } catch (UnsupportedEncodingException ignored) {
        }
        return value;
    }

}
